﻿using Anke.SHManage.IDAL;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Anke.SHManage.MSSQLDAL
{
    public partial class C_AccidentDAL : BaseDAL<C_Accident>, IC_AccidentDAL
    {

        IDALContext dalContext = new DALContextFactory().GetDALContext();
        AKV7ManageEntities db = DBContextFactory.GetDBContext() as AKV7ManageEntities;
        public string getMaxAccidentID()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                SELECT isnull(max (ID),'0000000000000') 
                FROM C_Accident ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            string result = "";
            if (ds.Tables[0].Rows.Count > 0)
            {
                result = Convert.ToString(ds.Tables[0].Rows[0][0]);
            }
            return result;

        }
      
        /// <summary>
        /// 获取事故列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="total"></param>
        /// <param name="zcenterCode"></param>
        /// <param name="zstationCode"></param>
        /// <param name="zAccidentLevel"></param>
        /// <param name="zResponsibility"></param>
        /// <param name="zambCode"></param>
        /// <param name="zambNumb"></param>
        /// <param name="zAccidentTimeStart"></param>
        /// <param name="zAccidentTimeEnd"></param>
        /// <returns></returns>
        public object getAccidentList(int page, int rows, ref int total, string zcenterCode, string zstationCode, string zAccidentLevel, string zResponsibility, string zambCode, string zambNumb, DateTime zAccidentTimeStart, DateTime zAccidentTimeEnd, E_StatisticsPermisson em, string selfWorkCode, string selfCenterID, string selfStationID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select distinct identity(int,1,1) as 行号,
                                 ca.ID,
                               ca.AmbulanceCode
                              ,ca.CenterCode
                             ,tc.名称 as Center
                              ,ca.StationCode, ts.名称 as Station 
                              ,CAE.PlateNumber
                              ,CAE.CarNumber
                            ,AccidentTime
                            ,AccidentAddress
                            ,AccidentLevel  ,tdB.Name as  AccidentLevelName
                            ,Responsibility, tdT.Name as  ResponsibilityName
                             ,tdbrand.Name as Brand
                             ,tdtype.Name as Type
                            ,ca.Remark         
                    into #temp
                    from  C_Accident  ca
                ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on ca.CenterCode=tc.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on ca.StationCode=ts.编码 ");
            sb.Append(@"
                        left join C_Ambulance CAE on ca.PlateNumber = CAE.AmbulanceCode
                        left join TDictionary  tdB  on ca.AccidentLevel  = tdB.ID
                        left join TDictionary  tdT  on ca.Responsibility  = tdT.ID
                        left join TDictionary  tdbrand on CAE.Brand = tdbrand.ID
                        left join TDictionary  tdtype on CAE.Type = tdtype.ID ");

            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("ca.AccidentTime", zAccidentTimeStart, sb);
            WhereClauseUtility.AddDateTimeLessThan("ca.AccidentTime", zAccidentTimeEnd, sb);

        
            WhereClauseUtility.AddStringEqual("ca.AccidentLevel", zAccidentLevel, sb);
            WhereClauseUtility.AddStringEqual("ca.Responsibility", zResponsibility, sb);

            WhereClauseUtility.AddStringLike("CAE.PlateNumber", zambCode, sb);
            WhereClauseUtility.AddStringLike("CAE.CarNumber", zambNumb, sb);

            if (em == E_StatisticsPermisson.None)
                return null;

            else
            {
                if (em == E_StatisticsPermisson.ALL)
                {
                    WhereClauseUtility.AddStringEqual("ca.CenterCode", zcenterCode, sb);
                    WhereClauseUtility.AddStringEqual("ca.StationCode", zstationCode, sb);


                }
                else if (em == E_StatisticsPermisson.CENTER)
                {
                    WhereClauseUtility.AddStringEqual("ca.CenterCode", selfCenterID, sb);
                    WhereClauseUtility.AddStringEqual("ca.StationCode", zstationCode, sb);

                }
                else if (em == E_StatisticsPermisson.STATION)
                {
                    sb.Append("and 1=2 ");
                    WhereClauseUtility.AddStringEqual("ca.CenterCode", zcenterCode, sb);
                    WhereClauseUtility.AddStringEqual("ca.StationCode", selfStationID, sb);

                }
                else if (em == E_StatisticsPermisson.SELF)
                {
                    WhereClauseUtility.AddStringEqual("ca.CenterCode", selfCenterID, sb);
                    WhereClauseUtility.AddStringEqual("ca.StationCode", selfStationID, sb);
                }
            }
            sb.Append("order by ID desc");


            sb.Append(@" select top " + rows + " A.*  from #temp A where 行号>=" + (page - 1) * rows + " order by 行号 ");
            sb.Append(@"  SELECT count(*) FROM #temp t   drop table #temp ");

            List<C_Accident> list = new List<C_Accident>();
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    C_Accident info = new C_Accident();
                    info.ID = dr["ID"].ToString();
                    info.AmbulanceCode = dr["AmbulanceCode"].ToString();
                    info.backup1 = dr["Center"].ToString();
                    info.EndReportPerson = dr["Station"].ToString();
                    info.PlateNumber = dr["PlateNumber"].ToString();
                    info.CarNumber = dr["CarNumber"].ToString();
                    var aaa = Convert.ToDateTime(dr["AccidentTime"]);
                    info.InsuranceExplain = Utility.DBConvert.ConvertDateTimeToNullable(aaa);
                    info.AccidentAddress = dr["AccidentAddress"].ToString();
                    info.Responsibility = dr["ResponsibilityName"].ToString();
                    info.AccidentLevel = dr["AccidentLevelName"].ToString();
                    info.ReportNumber = dr["Brand"].ToString();
                    info.PersonName = dr["Type"].ToString();
                    info.Remark = dr["Remark"].ToString();
                
                    list.Add(info);
                }
            }
            total = Convert.ToInt32(ds.Tables[1].Rows[0][0]);

            return list;

        }


        /// <summary>
        /// 根据ID 获取事故表全部内容，返回C_Accident info
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="info"></param>
        public void getEditACD(string ID, out C_Accident info)
        {
            info = (from a in db.C_Accident
                    where (a.ID.Equals(ID))
                    select a).FirstOrDefault().ToPOCO();
        }
    }
}
